<template>
  <div class="wangeditor" style="border: 1px solid #ccc;">
    <WEToolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" />
    <WEditor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
      @onCreated="handleCreated" />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css


// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('<p></p>')

// 上传Token
const uploadToken = ref(null);
// 获取本地token
const tokenInfo: any = localStorage.getItem('token');
let token: any = ''
if (tokenInfo !== null || tokenInfo !== undefined) {
  // 本地存在token信息，格式化token
  token = JSON.parse(tokenInfo);
  token = token.token_type + ' ' + token.access_token
  uploadToken.value = token;

}
// 设置编辑器默认内容
// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = props.initialContent
  }, 1500);
})
// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: upload2CloudFlare,
      fieldName: 'file',
      maxNumberOfFiles: 1,
      allowedFileTypes: ['image/*'],
      headers: {
        Authorization: uploadToken.value,
      },
      meta: {
        dir: 'content'
      }
    }
  }
}



const toolbarConfig = {}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}


// 定义prop
const props = defineProps({
  initialContent: {
    type: String,
    default: ''
  }
})

// 定义emits
watch(props, (newProps, oldProps) => {
  valueHtml.value = newProps.initialContent  
})
// 暴漏数据
defineExpose({
  valueHtml,
})
</script>

<style lang="scss" scoped></style>